﻿using System;
using System.Linq;
using Linq.Flickr;
using LinqExtender;
using log4net;
using People=FlickrXplorer.Web.ViewData.People;

namespace FlickrXplorer.Web.Models
{
    public class SecurityModel : ISecurityModel
    {
        private readonly FlickrContext context = null;
        private readonly ILog log = LogManager.GetLogger("SecurityModel");

        public SecurityModel()
        {
            context = new FlickrContext();
            context.Peoples.OnError += new Query<Linq.Flickr.People>.ErrorHandler(ShowException);
        }

        private void ShowException(ProviderException ex)
        {
            log.Error("Error processing user", ex);
            // throw.
            throw new Exception(ex.Message);
        }

        public People GetAuthenticatedUser()
        {
            People p = null;

            if (context.IsAuthenticated())
            {
                var query = from people in context.Peoples
                            select new People
                                       {
                                           RealName = people.RealName,
                                           Username = people.Username,
                                           IsPro = people.IsPro,
                                           Location = people.Location,
                                           ProfileUrl = people.ProfileUrl
                                       };

                p = query.Single();
            }
            return p;
        }

        public bool IsAthenticated()
        {
            return context.IsAuthenticated();
        }

        public bool ClearToken()
        {
            return context.ClearToken();
        }
    }

}
